<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="getHasSearchValues(state.query)"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="subjectType" label="权限来源">
          <FISelect
            v-model="state.query.subjectType"
            :options="[
              { value: 'USER_GROUP', label: '用户组' },
              { value: 'POST', label: '岗位' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="subjectEName" label="授权主体编码">
          <FIInput v-model="state.query.subjectEName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="resourceEName" label="资源编码">
          <FIInput v-model="state.query.resourceEName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="objectCName" label="资源名称">
          <FIInput v-model="state.query.objectCName" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="岗位和用户组权限审计列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      :insertable="false"
      :checkMode="'index'"
      primaryKey="formId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
      <template #headerBtn>
        <FIButton id="export" border class="margin-left5" @click="exportRow"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'

import LocalCache from '@/utils/cache'
import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, getHasSearchValues } from '@/utils/common'

import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiPostgroupAuthAudit, apiPostgroupAuthExport } from '@/api/user'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const apiUrl = proxy.$Button_api('query', route.name)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'postuserAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    subjectType: '',
    subjectEName: '',
    resourceEName: '',
    objectCName: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '权限来源',
    prop: 'subjectType',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: false,
    filterable: false,
    readonly: true,
    editType: 'select',
    modelValue: { inputValue: '' },
    editConfig: {
      options: [
        { value: 'USER_GROUP', label: '用户组' },
        { value: 'POST', label: '岗位' },
      ],
    },
  },
  {
    label: '授权主体编码',
    prop: 'subjectEName',
    align: 'center',
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '授权主体名称',
    prop: 'subjectCName',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    filterable: false,
    sortable: false,
    sortValue: '',
    modelValue: { inputValue: '' },
  },
  {
    label: '资源编码',
    prop: 'resourceEName',
    align: 'center',
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '资源名称',
    prop: 'objectCName',
    align: 'center',
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '资源类型',
    prop: 'resourceType',
    align: 'center',
    editType: 'select',
    modelValue: { inputValue: '' },
    editConfig: {
      options: [
        { value: 'BUTTON', label: '按钮' },
        { value: 'PAGE', label: '页面' },
      ],
    },
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  // apiRequestPost('/pageMaint/save', checkedRows.value)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       // saveSuccessful.value = true
  //       tableRef.value.clearSelection()
  //       searchFn()
  //     } else {
  //       ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //   })
}
const exportRow = () => {
  const apiUrl = proxy.$Button_api('export', route.name)
  apiRequestExport(apiUrl, state.query)
  // apiPostgroupAuthExport(state.query)
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
